package com.jilujia.domain.hotel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.jilujia.domain.hotel.repository.HotelViewCountRepository;
import com.jilujia.framework.domain.AbstractPoEntityManager;
import com.jilujia.web.CacheConstants;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class HotelViewCountManager extends AbstractPoEntityManager<Long, HotelViewCount, HotelViewCountRepository> {

	@Autowired
	private CacheManager cacheManager;

	@Cacheable(value = CacheConstants.HOTELS_VIEWCOUNT_CACHENAME, key = "'hotel_viewcount:'+#hotelId")
	public Integer getViewCount(Long hotelId) {
		Assert.notNull(hotelId, "Required hotelId must not be null");
		HotelViewCount hotelViewCount = this.findViewCountByHotelId(hotelId);
		Integer viewCount = 0;
		if (hotelViewCount != null) {
			viewCount = this.getInstance().getViewCount();
		}
		return viewCount;
	}

	public void addViewCount(Long hotelId) {
		Assert.notNull(hotelId, "Required instance's id must not be null");

		String key = "hotel_viewcount:" + hotelId;
		Integer viewCount = (Integer) cacheManager.getCache(CacheConstants.HOTELS_VIEWCOUNT_CACHENAME).get(key).get();
		viewCount = viewCount + 1;
		cacheManager.getCache(CacheConstants.HOTELS_VIEWCOUNT_CACHENAME).put(key, viewCount);

	}

	// public Integer subViewCount(Long hotelId) {
	// Assert.notNull(hotelId, "Required instance's id must not be null");
	//
	// String key = "hotel_viewcount:" + hotelId;
	// Integer viewCount = (Integer) cacheManager.getCache(HOTEL_VIEWCOUNT_CACHE_NAME).get(key).get();
	// viewCount = viewCount - 1;
	// cacheManager.getCache(HOTEL_VIEWCOUNT_CACHE_NAME).put(key, viewCount);
	//
	// return viewCount;
	// }

	public HotelViewCount findViewCountByHotelId(Long hotelId) {
		Assert.notNull(hotelId, "Required instance's id must not be null");

		HotelViewCount hotelViewCount = this.getRepository().findHotelViewCountByHotelId(hotelId);
		this.setInstance(hotelViewCount);
		return hotelViewCount;
	}

	@CacheEvict(value = CacheConstants.HOTELS_VIEWCOUNT_CACHENAME, key = "'hotel_viewcount:'+#hotelId")
	public void save(Long hotelId, Integer viewCount) {
		HotelViewCount hotelViewCount = this.findViewCountByHotelId(hotelId);
		if (hotelViewCount == null) {
			hotelViewCount = new HotelViewCount();
		}
		hotelViewCount.setHotelId(hotelId);
		hotelViewCount.setViewCount(viewCount);
		this.setInstance(hotelViewCount);
		this.save();
	}
}
